<script>
import { BASE_URL } from "@/util/Config.js";
export default {
  data() {
    return {
      comments: [], // 存储评论列表（从data.list获取）
      total: 0, // 总评论数
      isLoading: true,
      error: "" // 错误信息
    };
  },
  methods: {
    // 渲染星级评分（根据commentStar显示对应星星）
    renderStars(starCount) {
      let stars = [];
      // 最多5颗星
      for (let i = 1; i <= 5; i++) {
        stars.push({
          active: i <= starCount, // 星星是否点亮
          index: i
        });
      }
      return stars;
    },

    async fetchComments() {
      try {
        this.isLoading = true;
        this.error = "";

        // 发送请求（携带serviceId）
        const response = await fetch(BASE_URL + "/services/showcomments", {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({ serviceId: this.$route.params.id })
        });

        if (!response.ok) throw new Error(`请求失败：${response.status}`);
        const result = await response.json();

        // 关键：评论列表在data.list中，而非直接在data中
        this.comments = result.data?.list || [];
        this.total = result.data?.total || 0; // 总评论数

        console.log("评论数据加载成功：", this.comments);

      } catch (err) {
        this.error = "加载评论失败，请稍后重试";
        console.error("错误详情：", err);
        this.comments = [];
        this.total = 0;
      } finally {
        this.isLoading = false;
      }
    }
  },
  mounted() {
    // 确保路由参数存在再请求
    if (this.$route.params.id) {
      this.fetchComments();
    } else {
      this.error = "缺少服务ID，无法加载评论";
      this.isLoading = false;
    }
  }
};
</script>

<template>
  <div class="comment-section">
    <!-- 标题和总评论数 -->
    <div class="comment-header">
      <h3>用户评论</h3>
      <p class="total-count" v-if="total > 0">
        共 {{ total }} 条评论
      </p>
    </div>

    <!-- 加载状态 -->
    <div class="loading-state" v-if="isLoading">
      <div class="spinner"></div>
      <p>加载评论中...</p>
    </div>

    <!-- 错误状态 -->
    <div class="error-state" v-if="error && !isLoading">
      <p>⚠️ {{ error }}</p>
    </div>

    <!-- 无评论状态 -->
    <div class="empty-state" v-if="!isLoading && !error && comments.length === 0">
      <p>暂无评论，快来发表第一条评论吧～</p>
    </div>

    <!-- 评论列表（核心） -->
    <div class="comments-list" v-if="!isLoading && !error && comments.length > 0">
      <div class="comment-item" v-for="comment in comments" :key="comment.commentId">
        <!-- 用户信息 -->
        <div class="user-info">
          <!-- 用户头像（处理相对路径） -->
          <img
              :src="BASE_URL + comment.userImg"
              :alt="comment.userName"
              class="avatar"
              @error="e => e.target.src = 'https://picsum.photos/200/200'"> <!-- 缺省头像 -->

          <div class="user-details">
            <p class="user-name">{{ comment.userName }}</p>
            <p class="comment-time">{{ comment.commentDateTime }}</p>
          </div>
        </div>

        <!-- 星级评分 -->
        <div class="star-rating">
          <span
              class="star"
              v-for="star in renderStars(comment.commentStar)"
              :key="star.index"
              :class="{ active: star.active }">
            ★
          </span>
        </div>

        <!-- 评论内容（支持HTML格式） -->
        <div class="comment-content" v-html="comment.commentContent"></div>

        <!-- 分隔线 -->
        <hr v-if="comment !== comments[comments.length - 1]">
      </div>
    </div>
  </div>
</template>

<style scoped>
.comment-section {
  max-width: 1000px;
  margin: 20px auto;
  padding: 0 20px;
}

.comment-header {
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.comment-header h3 {
  margin: 0;
  color: #333;
}

.total-count {
  color: #666;
  margin: 5px 0 0 0;
}

/* 加载状态 */
.loading-state {
  text-align: center;
  padding: 50px 0;
  color: #666;
}

.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 错误状态 */
.error-state {
  text-align: center;
  padding: 50px 0;
  color: #e74c3c;
  background-color: #fef0f0;
  border-radius: 4px;
}

/* 无评论状态 */
.empty-state {
  text-align: center;
  padding: 50px 0;
  color: #999;
  background-color: #f9f9f9;
  border-radius: 4px;
}

/* 评论列表 */
.comments-list {
  margin-top: 20px;
}

.comment-item {
  padding: 15px 0;
}

/* 用户信息 */
.user-info {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  margin-right: 10px;
  border: 1px solid #eee;
}

.user-details .user-name {
  font-weight: 600;
  color: #333;
  margin: 0;
}

.user-details .comment-time {
  color: #999;
  font-size: 12px;
  margin: 3px 0 0 0;
}

/* 星级评分 */
.star-rating {
  margin: 10px 0;
  color: #ddd;
}

.star-rating .star.active {
  color: #f39c12; /* 点亮的星星颜色 */
}

/* 评论内容 */
.comment-content {
  color: #333;
  line-height: 1.6;
  margin: 10px 0;
  padding-left: 50px; /* 与头像对齐 */
}

/* 分隔线 */
.comment-item hr {
  border: none;
  border-top: 1px solid #f5f5f5;
  margin: 15px 0;
}
</style>